<?php
/**
 * Controller de la Aplicacion.
 *
 *
 * @filesource          
 * @copyright		
 * @link		http://www.pragmatia.com Pragmatia
 * @package		sgpoj
 * @subpackage		
 * @version     1.1
 * @license		http://www.opensource.org/licenses/mit-license.php The MIT License
 * @author      Martin Radosta <mradosta@pragmatia.com>
 */


/**
 * Clase AppController
 *
 * @package		datagro
 * @subpackage	
 */

class AppController extends Controller
{
	var $helpers = array("Html", "Javascript", "Paginator", "Formato", "Presentacion", "Formulario", "Menu");

	var $paginate = array('limit' => 12);


	var $components = array('RequestHandler', 'Filtro', 'Formato', 'History');


    function beforeFilter() {
		
		if (strtolower($this->name) == "pagos" && strtolower($this->action) == "recibir") {
			return true;
		}
	
		if($this->name == "Publica" || $this->name == "P") {
			return true;
			//d($this);
			//$this->redirect('publica/index', null, true);
		}
		//Solo si es el login, no controlo ni audito nada (aun no hay usuario en el sistema) o es la parte publica
		if (($this->name == "Usuarios" && $this->action == "login") || $this->action == "" || ($this->name == "Sucesos" && $this->action == "recibir") || ($this->name == "Datos" && $this->action == "r")) {
			return true;
		}
		
		//Busco en la session el usuario logueado
		$usuario = $this->Session->read('Usuario');

		$datos = array();
		$datos['controlador'] = $this->name;
		$datos['accion'] = $this->action;

		if ($this->name == "Usurios" && $this->action == "logout") {
			$datos['tipo'] = dominio("tipo_auditoria", "Salida");
		}
		elseif ($this->name == "Sucesos" && $this->action == "recibir") {
			$datos['tipo'] = dominio("tipo_auditoria", "Ingreso Datos Remoto");
		}
		else {
			$datos['tipo'] = dominio("tipo_auditoria", "Uso");
		}

		if(!empty($usuario['usuarioAnterior']) && !empty($usuario['Auditar']['puedeDeseleccionar']) && !empty($usuario['Auditar']['omitirAuditoria']) && $usuario['Auditar']['puedeDeseleccionar'] && $usuario['Auditar']['omitirAuditoria']) {
			//no audito nada porque es un admin convertido...
		}
		else {
			//hago la auditoria propiamente dicha
			loadModel('Auditoria');
			$Auditoria =& new Auditoria(); 
			$Auditoria->auditar($usuario, $datos);

			loadModel('Ayuda');
			$Ayuda =& new Ayuda();
			$this->set("ayudas", $Ayuda->findAll());
		}
		
		//return true;

		if($this->Session->check('Usuario'))
		{
			return true;
			loadModel('Usuario');
			$Usuario =& new Usuario(); 
			$usuario = $this->Session->read('Usuario');
			//tiene permiso este usuario para este controlador?
			if ($Usuario->validarIngreso($usuario, $this->name)) 
			{
				return true;
			}
			else
			{
				$this->redirect('../index.php', null, true);
			}
		}
		else
		{
			//$this->layout="login";
			//$this->redirect('../usuarios/login', null, true);
			$this->Session->setFlash('Su sesion ha expirado.', 'ok');
			$this->redirect('../index.php', null, true);
		}
    }

/**
 * La sobreescribo por bug en el framework que olvida las condiciones
 * Cambio la linea $vars = array('fields', 'order', 'limit', 'page', 'recursive');
 * por la linea    $vars = array('fields', 'order', 'limit', 'page', 'recursive', 'conditions');
 * Handles automatic pagination of model records
 *
 * @param mixed $object
 * @param mixed $scope
 * @param array $whitelist
 * @return array Model query results
 */
	function paginate($object = null, $scope = array(), $whitelist = array()) {

		if(isset($this->params['pass']['conditions']))
			$this->data = $this->Filtro->generarData($this->params['pass']['conditions']);

		if (is_array($object)) {
			$whitelist = $scope;
			$scope = $object;
			$object = null;
		}

		if (is_string($object)) {
			if (isset($this->{$object})) {
				$object = $this->{$object};
			} elseif (isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$object})) {
				$object = $this->{$this->modelClass}->{$object};
			} elseif (!empty($this->uses)) {
				for ($i = 0; $i < count($this->uses); $i++) {
					$model = $this->uses[$i];
					if (isset($this->{$model}->{$object})) {
						$object = $this->{$model}->{$object};
						break;
					}
				}
			}
		} elseif (empty($object) || $object == null) {
			if (isset($this->{$this->modelClass})) {
				$object = $this->{$this->modelClass};
			} else {
				$object = $this->{$this->uses[0]};
			}
		}

		if (!is_object($object)) {
			// Error: can't find object
			return array();
		}
		$options = am($this->params, $this->params['url'], $this->passedArgs);

		if (isset($this->paginate[$object->name])) {
			$defaults = $this->paginate[$object->name];
		} else {
			$defaults = $this->paginate;
		}

		if (isset($options['show'])) {
			$options['limit'] = $options['show'];
		}

		if (isset($options['sort']) && isset($options['direction'])) {
			$options['order'] = array($options['sort'] => $options['direction']);
		} elseif (isset($options['sort'])) {
			$options['order'] = array($options['sort'] => 'asc');
		}

		if (!empty($options['order']) && is_array($options['order'])) {
			$key = key($options['order']);
			if (strpos($key, '.') === false && $object->hasField($key)) {
				$options['order'][$object->name . '.' . $key] = $options['order'][$key];
				unset($options['order'][$key]);
			}
		}

		$vars = array('fields', 'order', 'limit', 'page', 'recursive', 'conditions');
		$keys = array_keys($options);
		$count = count($keys);

		for($i = 0; $i < $count; $i++) {
			if (!in_array($keys[$i], $vars)) {
				unset($options[$keys[$i]]);
			}
			if (empty($whitelist) && ($keys[$i] == 'fields' || $keys[$i] == 'recursive')) {
				unset($options[$keys[$i]]);
			} elseif (!empty($whitelist) && !in_array($keys[$i], $whitelist)) {
				unset($options[$keys[$i]]);
			}
		}

		$conditions = $fields = $order = $limit = $page = $recursive = null;
		if (!isset($defaults['conditions'])) {
			$defaults['conditions'] = array();
		}

		extract($options = am(array('page' => 1, 'limit' => 20), $defaults, $options));
		if (is_array($scope) && !empty($scope)) {
			$conditions = am($conditions, $scope);
		} elseif (is_string($scope)) {
			$conditions = array($conditions, $scope);
		}
		$recursive = $object->recursive;

		//MR 
		//unserialize casero porque el serialize no srive debido a que usa caracteres "prohibidos" para urls
		if(!empty($conditions))
		{
			$tmp = explode("*|*", $conditions);
			//d($tmp);
			$conditions = false;
			foreach($tmp as $k=>$v)
			{
				$tmp1 = explode("|", $v);
				//str_replace($tmp1[1], 
				if(isset($tmp1[0]) && isset($tmp1[1]) && !empty($tmp1[0]) && (!empty($tmp1[1]) || $tmp1[1] == "0")) {
					if(strstr($tmp1[1], "**--**")) {
							$conditions[$tmp1[0]] = explode("**--**", $tmp1[1]);
					}
					else {
						if(isset($conditions[$tmp1[0]])) {
							$cond = $conditions[$tmp1[0]];
							unset($conditions[$tmp1[0]]);
							$conditions[] = array("and"=> array(array($tmp1[0] => $tmp1[1]), array($tmp1[0]=>$cond)));
						}
						else
							$conditions[$tmp1[0]] = str_replace("_expandir_","%",$tmp1[1]);
					}
				}
			}
		}

		//d($conditions);
		$count = $object->findCount($conditions, $recursive);
		$pageCount = ceil($count / $limit);

		if($page == 'last') {
			$options['page'] = $page = $pageCount;
		}

		$results = $object->findAll($conditions, $fields, $order, $limit, $page, $recursive);
		$paging = array(
			'page'		=> $page,
			'current'	=> count($results),
			'count'		=> $count,
			'prevPage'	=> ($page > 1),
			'nextPage'	=> ($count > ($page * $limit)),
			'pageCount'	=> $pageCount,
			'defaults'	=> am(array('limit' => 20, 'step' => 1), $defaults),
			'options'	=> $options
		);

		$this->params['paging'][$object->name] = $paging;

		if (!in_array('Paginator', $this->helpers) && !array_key_exists('Paginator', $this->helpers)) {
			$this->helpers[] = 'Paginator';
		}

		return $results;
	}
}
?>